﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;
using TTJ.DataModel;
using TTJ.DataModel.DataStruct.Unsplash;

namespace TTJ.Service.Unsplash
{
    public partial class UnsplashHelper
    {
        public UnsplashQueryData Query(string keyword)
        {
            UnsplashQueryData result = null;
            if (string.IsNullOrEmpty(keyword)) return result;

            string enKeyWords = TranslateHelper.getTranslatedKeyword(keyword);
            string url = UrlBase + "/search/photos?query=" + enKeyWords + "&client_id=" + AppId;
            try
            {
                HttpWebRequest getAccessRequest = WebRequest.Create(url) as HttpWebRequest;
                //getAccessRequest.Proxy = null;
                getAccessRequest.ContentType = "multipart/form-data";
                getAccessRequest.Timeout = 30000;//30秒连接不成功就中断 
                getAccessRequest.Method = "get";

                HttpWebResponse response = getAccessRequest.GetResponse() as HttpWebResponse;
                using (StreamReader strHttpComback = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                {
                    string jsonResult = strHttpComback.ReadToEnd();
                    //解析json  
                    JavaScriptSerializer jss = new JavaScriptSerializer();
                    result = jss.Deserialize<UnsplashQueryData>(jsonResult);
                }
            }
            catch (WebException ex)
            {

            }
            return result;
        }
        public override TagImageList GetImageList(string keywords, int page = 0, int pagesize = 0)
        {
            UnsplashQueryData queryResult = Query(keywords);

            List<ImageData> list = new List<ImageData>();
            foreach (var item in queryResult.results)
            {
                ImageData image = new ImageData();
                image.User = item.user.name;
                image.From = FROM;
                image.Url_Small = item.urls.small;
                image.Url_Large = item.urls.raw;
                list.Add(image);
            }

            TagImageList result = new TagImageList();
            result.Total = queryResult.total;
            result.ImageList = list;
            return result;
        }
    }
}